<?php
error_reporting(E_ERROR | E_PARSE);
//test_tokens script script created by Robert Cox on April 12th 2011
//Commandline Usage: ./test_tokens.php commandline (debug)
//URL Usage: http://.../../test_tokens.php?web=1              <= normal mode
//      -or- http://.../../test_tokens.php?web=1&debug=1      <= debug mode

// set start time
$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;

if(isset($_GET['debug'])){
                $debug = TRUE;
                $GLOBALS["debug"] = TRUE;
        } else {
                unset($debug);
        }

if(isset($_GET['web'])){
                $web = TRUE;
                $GLOBALS["web"] = TRUE;
        } else {
                unset($web);
        }


if (isset($debug)) { 
	echo "<br>* * * * *  D E B U G = O N * * * * *<br>";
	if (isset($web)) { 
		echo "<br>* * * * *  W E B = O N  * * * * *<br>";}
}

$status = "";
$testname = "PhotoBucket Companion Test";
$testdesc = "Verify that companion ads are working for Photobucket";
$testurl = "test_pbkt_companion.php";
$testtime = time();

// Setup the archival file name for the test
$datestamp = date("YmdGis",$testtime);
$tokendate = date("Y-m-d",$testtime);
$tokentime = date("G:i:s",$testtime);

$directory = "/http/matchtest/archived_results/pbktcompaniontest/";

if(!is_dir($directory)){
	if(!mkdir($directory, 0777)) {
		die('Failed to create directory: '.$directory);
	}
}

$today = date("F j, Y, g:i a");
$random = rand();
$Mid = rand();
$ViewID = rand();
$ViewID1 = rand();

$UserAgent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16";

function TraceInfo($output,$string,$debug) {
        $line_match = array_values(preg_grep("/$string/", $output));
            if (isset($GLOBALS["debug"])) { echo "DEBUG - string:  ".$string."<br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - output:  <br><pre>"; print_r($output); echo "</pre><br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - line_match:<br><pre>"; print_r($line_match); echo "</pre><br>";}
			$result = $line_match[1];
        if (isset($GLOBALS["debug"])) { echo "DEBUG - result:  ".$result."<br>";}
		return $result;
}

function MakeRequest($AdCall, $debug) {
		$url = $AdCall."/trace=1/nolog";

        // initilize the curl call
        $ch = curl_init();
        // Set curl to use $url for http call
        curl_setopt($ch, CURLOPT_URL, $url);
        // show client headers
        curl_setopt($ch, CURLOPT_HEADER, 1);
        // have curl put X-Forwarded-For into headers
        curl_setopt($ch,CURLOPT_HTTPHEADER, $client_headers);
        // store results as the return of curl_exec
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // Follow redirects
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);		
        // if HTML error 400 over over, fail
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
		// execute the curl command with the defined URL
        $output = curl_exec($ch);
        if (isset($debug)) { echo "<br><pre><hr>HTTP Response Output:<br><br>"; print_r($output); echo "</pre><br><hr>"; }

        $output_array = preg_split('/[\n]/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
		
        if (isset($debug)) { echo "<br><pre><hr>HTTP Response Output (array):<br><br>"; print_r($output_array); echo "</pre><br><hr>"; }

        //get curl info
        $info = curl_getinfo($ch);
        if (isset($debug)) { echo "<br><pre><hr>CURL Response Info:<br><br>"; print_r($info); echo "</pre><br><hr>"; }

        //close curl connection
        curl_close($ch);

        /** get HTTP return header (code AND text) **/

        $http_response = array_values(preg_grep("/^HTTP/", $output_array));
        $http_array = explode(" ",$http_response[0]);
        $http_return_code = trim($http_array[1]);
        $http_return_text = trim($http_array[2]);
        if (isset($debug)) { echo "<br>DEBUG - HTTP CODE/TEXT: $http_response[0]<br>"; }

        /* check code = 200 and text equal OK, anything else we have an error */

        if ($http_return_text != "OK" || $http_return_code != "200") {
            if (isset($debug)) { echo "***** ALERT - HTTP CODE/TEXT: ".trim($http_response[0])." *****<br>"; }
				echo "HTTP return code/text was not 200/OK". trim($http_response[0])."<br>";
                die;
        }
		
	return $output_array;
}

function ArrayToText($output_array){
		// count the number of elements in the response array
		$num_elements = count($output_array);
        if (isset($debug)) { echo "The Number Of Elements in the OUTPUT Array are: ".$num_elements." <br>"; }
		
		// format the items in the array as a long concatenated string.
		$y=0;
		while($y <= $num_elements){
			$formatted_output = $formatted_output.$output_array[$y]."\n";
			$formatted_output_web = $formatted_output_web.$output_array[$y]."<br>";
			$y++;
		}
        if (isset($debug)) { echo "The Formatted contents of OUTPUT are: ".$formatted_output_web." *****<br>"; }
		
	return $formatted_output;
}

function GetFCID($TraceTargeting) {
	$explode = explode(" ", $TraceTargeting);
	return $explode[7];
}

// setup command line args (commandline only)

if (isset($argv[1])) { $commandline = $argv[1]; unset($debug);} 

        $AdCallURL = "http://b.photobucket.com";
		$Directive = "/pbkt/hserver/";
		$PathInfoBanner = "mid=".$Mid."/viewid=".$ViewID."/size=BANNER/reg_zip=empty/search_kw=travel/user_kw=empty/sp=f/bf=empty/ptype=landing/spon=empty/track=empty/ref_domain=empty/random=".$random."/area=fs_travel/login=N/site=pb/anprice=200";
		$PathInfoRectangle = "mid=".$Mid."/viewid=".$ViewID."/size=RECTANGLE/reg_zip=empty/search_kw=travel/user_kw=empty/sp=f/bf=empty/ptype=landing/spon=empty/track=nav/ref_domain=empty/random=".$random."/area=fs_travel/login=N/site=pb/anprice=200";
		$PathInfoPromo = "mid=".$Mid."/viewid=".$ViewID1."/size=PROMO/reg_zip=empty/search_kw=travel/user_kw=empty/sp=f/bf=empty/ptype=landing/spon=empty/track=empty/ref_domain=empty/random=".$random."/area=fs_travel/login=N/site=pb";
        $client_headers[] = sprintf('X-Forwarded-For: %s', $ClientIP);

		$output468x60 = MakeRequest($AdCallURL.$Directive.$PathInfoBanner,$debug);
        $TraceTargeting468x60 = TraceInfo($output468x60,">>>>");
		$FCID468x60 = GetFCID($TraceTargeting468x60);
        if (isset($debug)) { echo "TraceTargeting = ".$TraceTargeting468x60."<br>FCID = ".$FCID468x60."<br>"; }
		$FormattedOutput468x60 = ArrayToText($output468x60);
        if (isset($debug)) { echo "<pre>The Formatted contents of OUTPUT468x60 are: <br>".$FormattedOutput468x60."</pre><br>"; }
		
		$output125x125 = MakeRequest($AdCallURL.$Directive.$PathInfoRectangle,$debug);
        $TraceTargeting125x125 = TraceInfo($output125x125,">>>>");
		$FCID125x125 = GetFCID($TraceTargeting125x125);
        if (isset($debug)) { echo "TraceTargeting = ".$TraceTargeting125x125."<br>FCID = ".$FCID125x125."<br>"; }
		$FormattedOutput125x125 = ArrayToText($output125x125);
        if (isset($debug)) { echo "<pre>The Formatted contents of OUTPUT125x125 are: <br>".$FormattedOutput125x125."</pre><br>"; }
	
		$output160x600 = MakeRequest($AdCallURL.$Directive.$PathInfoPromo,$debug);
        $TraceTargeting160x600 = TraceInfo($output160x600,">>>>");
		$FCID160x600 = GetFCID($TraceTargeting160x600);
        if (isset($debug)) { echo "TraceTargeting = ".$TraceTargeting160x600."<br>FCID = ".$FCID160x600."<br>"; }
		$FormattedOutput160x600 = ArrayToText($output160x600);
        if (isset($debug)) { echo "<pre>The Formatted contents of OUTPUT160x600 are: <br>".$FormattedOutput160x600."</pre><br>"; }
		
		
// Determine if the test was successful
		if($FCID468x60 == 24){  // White Companion (not loose or strict) 
			if(($FCID125x125 == 10) || ($FCID125x125 == 7)){  // Should not have served a STRICT ad.
				$status = "fail";
				$reason = "White Companion Ad Served in the 468x60 spot and then a STRICT Ad Served in the 125x125 spot";
			}
			else if (($FCID125x125 == 25) || ($FCID125x125 == 14) || ($FCID125x125 == 20) || ($FCID125x125 == 16)){     
				if (($FCID160x600 == 26) || ($FCID160x600 == 13) || ($FCID160x600 == 18) || ($FCID160x600 == 17)){ 
					$status = "pass";
				}
				else {
					$status = "fail";
					$reason = "2";
				}
			}
			else {
				$status = "fail";
				$reason = "3";
			}
		}
		else if($FCID468x60 == 12){ // Yellow LOOSE
			if(($FCID125x125 == 10) || ($FCID125x125 == 7)){  // Should NOT have served a STRICT ad.
				$status = "fail";
				$reason = "4";
			}
			else if ($FCID125x125 == 14){     // Serve the next Yellow LOOSE Ad
				if ($FCID160x600 == 13){ 	  // Serve the last Yellow LOOSE Ad
					$status = "pass";
				}
				else {
					$status = "fail";
					$reason = "5";
				}
			}
			else {
				$status = "fail";
				$reason = "6";
			}
		}
		else if($FCID468x60 == 19){
			if(($FCID125x125 == 10) || ($FCID125x125 == 7)){  // Should NOT have served a STRICT ad.
				$status = "fail";
				$reason = "7";
			}
			else if ($FCID125x125 == 20){     // Serve the next Green LOOSE Ad
				if ($FCID160x600 == 18){ 	  // Serve the last Green LOOSE Ad
					$status = "pass";
				}
				else {
					$status = "fail";
					$reason = "8";
				}
			}
			else {
				$status = "fail";
				$reason = "9";
			}
		}
		else if($FCID468x60 == 15){
			if(($FCID125x125 == 10) || ($FCID125x125 == 7)){  // Should NOT have served a STRICT ad.
				$status = "fail";
				$reason = "10";
			}
			else if ($FCID125x125 == 16){     // Serve the next Brown LOOSE Ad
				if ($FCID160x600 == 17){ 	  // Serve the last Brown LOOSE Ad
					$status = "pass";
				}
				else {
					$status = "fail";
					$reason = "11";
				}
			}
			else {
				$status = "fail";
				$reason = "12";
			}
		}
// If a Strict Ad was served
		else if($FCID468x60 == 9){
			if(($FCID125x125 == 25) || ($FCID125x125 == 14) || ($FCID125x125 == 20) || ($FCID125x125 == 16)){  // Should NOT have served a LOOSE ad.
				$status = "fail";
				$reason = "13";
			}
			else if ($FCID125x125 == 10){     // Serve the next Red STRICT Ad
				if ($FCID160x600 == 11){ 	  // Serve the last Red STRICT Ad
					$status = "pass";
					$reason = "14";
				}
				else {
					$status = "fail";
					$reason = "15";
				}
			}
			else {
				$status = "fail";
				$reason = "16";
			}
		}
		else if($FCID468x60 == 8){
			if(($FCID125x125 == 25) || ($FCID125x125 == 14) || ($FCID125x125 == 20) || ($FCID125x125 == 16)){  // Should NOT have served a LOOSE ad.
				$status = "fail";
				$reason = "17";
			}
			else if ($FCID125x125 == 7){     // Serve the next Red STRICT Ad
				if ($FCID160x600 == 6){ 	  // Serve the last Red STRICT Ad
					$status = "pass";
					$reason = "18";
				}
				else {
					$status = "fail";
					$reason = "19";
				}
			}
			else {
				$status = "fail";
				$reason = "20";
			}
		}
		else{
			$status = "fail";
			$reason = "21";
		}


// Determine if the test was successful

	if (isset($debug)) { echo "Test Summary:<br>"; }
	if (isset($debug)) { echo "Status: ".$status."<br>"; }
	if (isset($debug) && $status == "fail") { echo "Reason for Failure: ".$reason."<br>"; }

	
	$ArchiveOutputFile = "Test Summary: \n    Status: ".$status."\n";
    if ($status == "fail") { $ArchiveOutputFile = $ArchiveOutputFile."    Reason for Failure: ".$reason."\n\n"; }
	$ArchiveOutputFile = $ArchiveOutputFile."468x60 = ".$TraceTargeting468x60."\nFCID = ".$FCID468x60."\n\n";
	$ArchiveOutputFile = $ArchiveOutputFile."125x125 = ".$TraceTargeting125x125."\nFCID = ".$FCID125x125."\n\n";
	$ArchiveOutputFile = $ArchiveOutputFile."160x600 = ".$TraceTargeting160x600."\nFCID = ".$FCID160x600."\n\n-----------------------------------";
	$ArchiveOutputFile = $ArchiveOutputFile."Detailed Results 468x60:\n\n".$FormattedOutput468x60."\n\n-----------------------------------";
	$ArchiveOutputFile = $ArchiveOutputFile."Detailed Results 125x125:\n\n".$FormattedOutput125x125."\n\n-----------------------------------";
	$ArchiveOutputFile = $ArchiveOutputFile."Detailed Results 160x600:\n\n".$FormattedOutput160x600."\n\n-----------------------------------";

	if ($status == "pass") { $ArchiveOutputWeb = "<font size=\"3\"><b>Test Summary:</b></font><br>&nbsp;&nbsp;&nbsp;&nbsp;<font size=\"3\" color=\"green\"><b>Status: ".$status."</b></font><br>"; }
	if ($status == "fail") { $ArchiveOutputWeb = "<font size=\"3\"><b>Test Summary:<b></font><br>&nbsp;&nbsp;&nbsp;&nbsp;<font size=\"3\" color=\"red\"><b>Status: ".$status."</b></font><br>"; }
    if ($status == "fail") { $ArchiveOutputWeb = $ArchiveOutputWeb."&nbsp;&nbsp;&nbsp;&nbsp;Reason for Failure: ".$reason."<br><br>"; }
	$ArchiveOutputWeb = $ArchiveOutputWeb."<br>468x60 = ".$TraceTargeting468x60."<br>FCID = ".$FCID468x60."<br>";
	$ArchiveOutputWeb = $ArchiveOutputWeb."<br>125x125 = ".$TraceTargeting125x125."<br>FCID = ".$FCID125x125."<br>";
	$ArchiveOutputWeb = $ArchiveOutputWeb."<br>160x600 = ".$TraceTargeting160x600."<br>FCID = ".$FCID160x600."<br>";
	$ArchiveOutputWeb = $ArchiveOutputWeb."<br><hr>Detailed Results 468x60:<pre>".$FormattedOutput468x60."</pre><hr>";
	$ArchiveOutputWeb = $ArchiveOutputWeb."Detailed Results 125x125:<pre>".$FormattedOutput125x125."</pre><hr>";
	$ArchiveOutputWeb = $ArchiveOutputWeb."Detailed Results 160x600:<pre>".$FormattedOutput160x600."</pre>";

	if (isset($web)) { echo $ArchiveOutputWeb; }
	
// Write out the information to the testresults.txt file.

$lines = file('/http/matchtest/testresults.txt');
$numitems = count($lines);

// Loop through our array, show HTML source as HTML source; and line numbers too.

if (isset($debug)) { echo "<br><pre><hr>HTTP Response Output:<br><br>"; print_r($lines); echo "</pre><br><hr>"; }

$newfile = $lines[0];
$i=1;
while($i <= $numitems) {
	$pieces = explode("|",$lines[$i]);
	if($testname == $pieces[1]){
		$replaced_line = $status."|".$testname."|".$testdesc."|".$testurl."|".$testtime."\n";
		$newfile = $newfile.$replaced_line;
	}
	else{
		$newfile = $newfile.$lines[$i];
	}
	$i++;
}

if (isset($debug)) { echo "<br><pre><hr>New File Output:<br><br>"; print_r($newfile); echo "</pre><br><hr>"; }

$fp = fopen('/http/matchtest/testresults.txt', 'w');

fwrite($fp, $newfile);
fclose($fp);

// Write out results of the test to a file 
if (isset($web)) { $testfilename = $directory."tokentest.web.".$status.".".$datestamp.".".$testtime.".txt"; }
if (isset($commandline)) { $testfilename = $directory."tokentest.commandline.".$status.".".$datestamp.".".$testtime.".txt"; }

if ($status == "fail") {
	if (!$fp1 = fopen($testfilename,'w')) {
		echo "Cannot open file ($testfilename)";
		exit;
	}

	fwrite ($fp1,$ArchiveOutputFile."\n\n");
	fclose($fp1);
}

if (isset($debug)) { phpinfo(); }
?>
